//
//  ZLPSubjectViewController.m
//  TangYi
//
//  Created by dllo on 15/10/27.
//  Copyright (c) 2015年 赵连鹏. All rights reserved.
//

#import "ZLPSubjectViewController.h"
#import "ZLPSubjectModel.h"
#import "PrefixHeader.pch"
#import <UIImageView+WebCache.h>
#import "ZLPSubjectTableViewCell.h"
#import "ZLPRankModel.h"
#import "ZLPRankViewController.h"
#import "ZLPTopicTableViewCell.h"
#import "ZLPDynamicModel.h"
#import "ZLPPicModel.h"
#import "ZLPAuthorModel.h"
#import "ZLPTopicModel.h"
#import "ZLPSubDetailViewController.h"
#import "UMSocial.h"
#import "ZLPIsLoginHandle.h"
#import <AFNetworking.h>

@interface ZLPSubjectViewController ()<UITableViewDataSource, UITableViewDelegate, ZLPSubjectTableViewCellDelegate, ZLPTopicTableViewCellDelegate>

@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) UICollectionView *collectView;
@property(nonatomic, retain) NSMutableArray *subjectArr;
@property(nonatomic, retain) UIImageView *imageView;
@property(nonatomic, retain) NSMutableArray *rankArr;
@property(nonatomic, retain) UIView *headView;
@property(nonatomic, retain) NSMutableArray *topicArr;
@property(nonatomic, retain) NSMutableArray *picArr;
@property(nonatomic, retain) NSMutableArray *dynamicArr;
@property(nonatomic, retain) NSMutableArray *authorArr;

@end

@implementation ZLPSubjectViewController

- (void)dealloc {
    [_picArr release];
    [_dynamicArr release];
    [_authorArr release];
    [_topicArr release];
    [_rankArr release];
    [_headView release];
    [_imageView release];
    [_subjectArr release];
    [_tableView release];
    [_collectView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"本期话题";
    
    [self createTableView];
    
    [self createHeadView];
    
//    [self isWlan];
    
    [self createData];

    
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            
            [self createData];
            
        } else {
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];

        }
        
    }];
}

- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 14) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
}

- (void)createHeadView {
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
    self.tableView.tableHeaderView = self.headView;
    [_headView release];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
    [self.headView addSubview:self.imageView];
    [_imageView release];
    
}

- (void)createData {
    NSString *strURL = @"http://open3.bantangapp.com/community/subject/info";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.0.1&screensize=640&subject_id=%@&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7", self.numID];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.subjectArr = [NSMutableArray array];
            ZLPSubjectModel *model = [[ZLPSubjectModel alloc] init];
            [model setValuesForKeysWithDictionary:dic[@"data"][@"subject"]];
            
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.pic2] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
            
            [self.subjectArr addObject:model];
            
            self.rankArr = [NSMutableArray array];
            self.rankArr = [ZLPRankModel baseModelByArr:dic[@"data"][@"subject"][@"dynamic"][@"rank_list"]];
            
            
            [self.tableView reloadData];
        } else {
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];
        }
        
    }];
    
    NSString *strUrl = @"http://open3.bantangapp.com/community/subject/listPost";
    NSURL *listURL = [NSURL URLWithString:strUrl];
    NSMutableURLRequest *listRequest = [NSMutableURLRequest requestWithURL:listURL];
    [listRequest setHTTPMethod:@"POST"];
    NSString *listBody = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.0.1&page=0&pagesize=10&screensize=640&subject_id=%@&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&type_id=0&v=7", self.numID];
    NSLog(@"%@", self.numID);
    NSData *listData = [listBody dataUsingEncoding:NSUTF8StringEncoding];
    [listRequest setHTTPBody:listData];
    [NSURLConnection sendAsynchronousRequest:listRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.topicArr = [NSMutableArray array];
            self.topicArr = [ZLPTopicModel baseModelByArr:dic[@"data"][@"list"]];
            
            self.picArr = [NSMutableArray array];
            self.authorArr = [NSMutableArray array];
            self.dynamicArr = [NSMutableArray array];
            
            for (NSDictionary *temp in dic[@"data"][@"list"]) {
                
                
                ZLPPicModel *picModel = [[ZLPPicModel alloc] init];
                [picModel setValuesForKeysWithDictionary:temp[@"pics"][0]];
                [self.picArr addObject:picModel];
                [picModel release];
                
                
                ZLPAuthorModel *authorModel = [[ZLPAuthorModel alloc] init];
                [authorModel setValuesForKeysWithDictionary:temp[@"author"] ];
                [self.authorArr addObject:authorModel];
                [authorModel release];
                
                
                ZLPDynamicModel *dynamicModel = [[ZLPDynamicModel alloc] init];
                [dynamicModel setValuesForKeysWithDictionary:temp[@"dynamic"]];
                [self.dynamicArr addObject:dynamicModel];
                [dynamicModel release];
                
                
            }
            
            
            [self.tableView reloadData];

        } else {
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];

        }
    }];

    
}
#pragma mark tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return self.topicArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *reuse = @"reuse";
        ZLPSubjectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ZLPSubjectTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        ZLPSubjectModel *model = [[ZLPSubjectModel alloc] init];
        model = self.subjectArr[0];
        cell.descLabel.text = model.desc;
        cell.descLabel.numberOfLines = 0;
        cell.rankLabel.text = @"排       行        榜";
        
        
        cell.rankArr = self.rankArr;
        
        cell.delegate = self;
        
        [cell.collectView reloadData];
        
        return cell;
    } else {
        static NSString *reuse = @"reuse2";
        ZLPTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ZLPTopicTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        
        cell.usernameLabel.text = [self.authorArr[indexPath.row] username];
        cell.timeLabel.text = [self.topicArr[indexPath.row] datestr];
        [cell.avaterImageView sd_setImageWithURL:[NSURL URLWithString:[self.authorArr[indexPath.row] avatar]]placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        ZLPPicModel *picModel = [[ZLPPicModel alloc] init];
        picModel = self.picArr[indexPath.row];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString: picModel.url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.descLabel.text = [self.topicArr[indexPath.row] content];
        cell.descLabel.numberOfLines = 0;
//        cell.commentLabel.text = [NSString stringWithFormat:@"评论 %@", [self.dynamicArr[indexPath.row] comments]];

        [cell.likesButton setTitle:[self.dynamicArr[indexPath.row] likes] forState:UIControlStateNormal];
        
        cell.delegate = self;
        cell.picModel = self.picArr[indexPath.row];
        cell.topicModel = self.topicArr[indexPath.row];
        
        return cell;
    }
}

- (void)click:(ZLPTopicModel *)model pic:(ZLPPicModel *)picModel {
 
//    if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin) {
    
        UMSocialUrlResource *urlResource = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeImage url:picModel.url];
        [UMSocialData defaultData].urlResource = urlResource;
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"563814b567e58efbc7003c2c"
                                          shareText:[NSString stringWithFormat:@"我在#糖衣#发现了一个好东西. %@", model.share_url]
                                         shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                           delegate:nil];
        
        
//    } else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请先登陆" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        ZLPSubDetailViewController *subDetailVC = [[ZLPSubDetailViewController alloc] init];
        [self.navigationController pushViewController:subDetailVC animated:YES];
        
        subDetailVC.numID = [self.topicArr[indexPath.row] numID];
        NSLog(@"%@", [self.topicArr[indexPath.row] numID]);
        
    }
}

- (void)pushCollentionView:(NSMutableArray *)rank_list {
    ZLPRankViewController *rankVC = [[ZLPRankViewController alloc] init];
    [self.navigationController pushViewController:rankVC animated:YES];
    rankVC.rankListArr = rank_list;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
// 指定分区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return @"精选";
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZLPSubjectModel *model = [[ZLPSubjectModel alloc] init];
        model = self.subjectArr[0];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
        CGRect rect = [model.desc boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        return rect.size.height + 90;
    } else {
        ZLPTopicModel *model = [[ZLPTopicModel alloc] init];
        model = self.topicArr[indexPath.row];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
        CGRect rect = [model.content boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return 520 + rect.size.height;
    }
    
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 24)];
    headView.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 24)];
    [headView addSubview:label];
    [label release];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 - 130, 12, 80, 3)];
    [headView addSubview:leftLabel];
    leftLabel.backgroundColor = [UIColor grayColor];
    [leftLabel release];
    
    UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 + 50, 12, 80, 3)];
    [headView addSubview:rightLabel];
    rightLabel.backgroundColor = [UIColor grayColor];
    [rightLabel release];
    
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"糖  衣  推  荐";
    label.textColor = [UIColor grayColor];
    
    return headView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
